﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;


namespace GS_OM.Pages
{
    /// <summary>
    ///Communal 的摘要说明
    /// </summary>
    public class Communal
    {
        //公用类

        public Communal()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 验证是否指定的图片格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsImage(string str)
        {

            bool isimage = false;
            string thestr = str.ToLower();
            //限定只能上传jpg和gif图片
            string[] allowExtension = { ".jpg", ".gif", ".bmp", ".png" };
            //对上传的文件的类型进行一个个匹对
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (thestr == allowExtension[i])
                {
                    isimage = true;
                    break;
                }
            }
            return isimage;
        }


        /// <summary>
        /// 创建一个指定长度的随机salt值
        /// </summary>
        public static string CreateSalt(int saltLenght)
        {
            //生成一个加密的随机数
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            byte[] buff = new byte[saltLenght];
            rng.GetBytes(buff);
            //返回一个Base64随机数的字符串
            return Convert.ToBase64String(buff);
        }

        /// <summary>
        /// 返回加密后的字符串
        /// </summary>
        public static string CreatePasswordHash(string pwd, int saltLenght)
        {
            string strSalt = CreateSalt(saltLenght);
            //把密码和Salt连起来
            string saltAndPwd = String.Concat(pwd, strSalt);
            //对密码进行哈希
            string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
            //转为小写字符并截取前16个字符串
            hashenPwd = hashenPwd.ToLower().Substring(0, 16);
            //返回哈希后的值
            return hashenPwd;
        }

        public static string UploadImg(Page Page, HttpPostedFile FuImage)
        {
            if (FuImage != null)//验证是否包含文件
            {
                string fileExtension = System.IO.Path.GetExtension(FuImage.FileName).ToLower(); //取得文件的扩展名,并转换成小写
                if (Communal.IsImage(fileExtension))
                {
                    string filepath = "../files/userImgPath/"+Page.Session["SID"]+"/";
                   
                    if (FuImage.ContentLength < 8192000) //对上传文件的大小进行检测，限定文件最大不超过8M
                    {
                        if (System.IO.Directory.Exists(Page.Server.MapPath(filepath)) == false)//如果不存在就创建file文件夹
                        {
                            System.IO.Directory.CreateDirectory(Page.Server.MapPath(filepath));
                        }
                        string virpath = filepath + CreatePasswordHash(FuImage.FileName, 4) + fileExtension;//这是存到服务器上的虚拟路径
                        string mappath = Page.Server.MapPath(virpath);//转换成服务器上的物理路径
                        if (!Directory.Exists(mappath))
                        FuImage.SaveAs(mappath);//上传
                        //FileStream fs = File.Open(mappath, FileMode.OpenOrCreate);
                        //System.Drawing.Image img = Image.FromStream(fs);
                        //Inscribe(img, 512);
                        //fs.Close();
                        //SaveToJpeg(img, mappath);
                        return "上传成功|" + virpath;
                    }
                    else
                    {
                        return "文件大小超出8M！请重新选择！";
                    }
                }
                else
                {
                    return "要上传的文件类型不对！请选择JPG,GIF,BMP或PNG格式的图片！";
                }
            }
            else
            {
                return "请选择要上传的文件！";
            }
        }

        //public static System.Drawing.Image Inscribe(Image image, int size)
        //{
        //    return Inscribe(image, size, size);
        //}

        //public static Image Inscribe(Image image, int width, int height)
        //{
        //    Bitmap result = new Bitmap(width, height);
        //    using (Graphics graphics = Graphics.FromImage(result))
        //    {
        //        double factor = 1.0 * width / image.Width;
        //        if (image.Height * factor < height)
        //            factor = 1.0 * height / image.Height;
        //        Size size = new Size((int)(width / factor), (int)(height / factor));
        //        Point sourceLocation = new Point((image.Width - size.Width) / 2, (image.Height - size.Height) / 2);

        //        SmoothGraphics(graphics);
        //        graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(sourceLocation, size), GraphicsUnit.Pixel);
        //    }
        //    return result;
        //}

        //static void SmoothGraphics(Graphics g)
        //{
        //    g.SmoothingMode = SmoothingMode.AntiAlias;
        //    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        //    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        //}

        //public static void SaveToJpeg(Image image, Stream output)
        //{
        //    image.Save(output, ImageFormat.Jpeg);
        //}

        //public static void SaveToJpeg(Image image, string fileName)
        //{
        //    image.Save(fileName, ImageFormat.Jpeg);
        //}

    }
}